﻿using CSRedis;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace SqlSugarRedisDemo
{
    public class SqlSugarRedisCache : ICacheService
    {
        public static CSRedisClient redisDb = new CSRedisClient("127.0.0.1:6379,writeBuffer=10240,ConnectTimeout=15000,SyncTimeout=5000,defaultDatabase=0");

        public void Add<V>(string key, V value)
        {
            redisDb.Set(key, value);
        }

        public void Add<V>(string key, V value, int cacheDurationInSeconds)
        {
            redisDb.Set(key, value, cacheDurationInSeconds);
        }

        public bool ContainsKey<V>(string key)
        {
            return redisDb.Exists(key);
        }

        public V Get<V>(string key)
        {
            return redisDb.Get<V>(key);
        }

        public IEnumerable<string> GetAllKey<V>()
        {
            return redisDb.Keys("*");
        }

        public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
        {
            var result = redisDb.Get<V>(cacheKey);
            if (result != null) 
            {
                return result;
            }
            result = create();
            redisDb.Set(cacheKey, result, cacheDurationInSeconds);
            return result;
        }

        public void Remove<V>(string key)
        {
            redisDb.Del(key);
        }
    }
}
